<template>
  <div>
    <!-- 🍞面包屑导航区 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 💳卡片视图区域 -->
    <el-card>
      <!-- 🧿搜索与添加区域 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            placeholder="请输入内容"
            v-model="queryInfo.query"
            clearable
            @clear="getUserList"
          >
            <template #append>
              <el-button :icon="Search" @click="getUserList" size="large" />
            </template>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="showAddDialog">添加用户</el-button>
        </el-col>
      </el-row>

      <!-- 📑用户列表区域 -->
      <el-table :data="userList" stripe border>
        <el-table-column type="index" label="#" />
        <el-table-column label="姓名😎" prop="username" />
        <el-table-column label="邮箱📭" prop="email" />
        <el-table-column label="电话📱" prop="mobile" />
        <el-table-column label="角色🧐" prop="role_name" />
        <el-table-column label="状态👌">
          <template #default="scope">
            <el-switch
              v-model="scope.row.mg_state"
              style="
                --el-switch-on-color: #13ce66;
                --el-switch-off-color: #ff4949;
              "
              @change="userStateChange(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作🤷‍♀️" width="180px">
          <template #default="scope">
            <!-- 修改 -->
            <el-button
              size="large"
              circle
              type="primary"
              :icon="Edit"
              @click="showEditDialog(scope.row.id)"
            />
            <!-- 删除 -->
            <el-button
              size="large"
              circle
              type="danger"
              :icon="Delete"
              @click="removeUserById(scope.row.id)"
            />
            <!-- 分配角色 -->
            <el-tooltip
              effect="dark"
              content="分配角色"
              placement="top"
              :enterable="false"
            >
              <el-button
                size="large"
                circle
                type="warning"
                :icon="Setting"
                @click="setRoles(scope.row)"
              />
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination
        v-model:currentPage="queryInfo.pagenum"
        v-model:page-size="queryInfo.pagesize"
        :page-sizes="[1, 2, 5, 10]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <!--* 添加用户 -->
    <el-dialog
      v-model="addDialogVisible"
      title="添加用户"
      width="50%"
      @close="addDialogClosed"
    >
      <el-form
        ref="addFormRef"
        :model="addForm"
        :rules="addFormRules"
        label-width="80px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email" />
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addForm.mobile" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="addUser"> 确认 </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- * 修改用户 -->
    <el-dialog
      v-model="editDialogVisible"
      title="修改用户"
      width="50%"
      @close="editFormClosed"
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="editFormRules"
        label-width="80px"
      >
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" disabled />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email" />
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editForm.mobile" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="editUser"> 确认 </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- * 分配角色 -->
    <el-dialog v-model="setRoleDialogVisible" title="分配角色" width="50%">
      <p>当前的用户：{{ userInfo.username }}</p>
      <p>当前的角色：{{ userInfo.role_name }}</p>
      <p>
        分配新角色：
        <el-select v-model="selectRoleId" placeholder="请选择">
          <el-option
            v-for="item in rolesList"
            :key="item.id"
            :label="item.roleName"
            :value="item.id"
          >
          </el-option>
        </el-select>
        <!-- {{ rolesList }} -->
      </p>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="setRoleDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveRoleInfo"> 确认 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { Search, Setting, Delete, Edit } from '@element-plus/icons-vue';
import { onBeforeMount, getCurrentInstance, reactive, ref } from 'vue';
import { ElMessage, ElMessageBox, selectKey } from 'element-plus';
const currentInstance = getCurrentInstance();
const { $axios } = currentInstance.appContext.config.globalProperties;

// *获取用户列表数据
const queryInfo = reactive({
  query: '',
  pagenum: 1,
  pagesize: 2,
});

let userList = ref([]);
let total = ref(0);
async function getUserList() {
  const { data } = await $axios.get('users', { params: queryInfo });
  if (data.meta.status !== 200)
    return ElMessage({
      type: 'error',
      showClose: true,
      message: '获取用户列表失败',
    });

  userList.value = data.data.users;
  total.value = data.data.total;
}
onBeforeMount(getUserList);

// pagesize
function handleSizeChange(newSize) {
  // console.log(newSize);
  queryInfo.pagesize = newSize;
  getUserList();
}
// pagenum
function handleCurrentChange(newPage) {
  queryInfo.pagenum = newPage;
  getUserList();
}
// switch
const userStateChange = async (userInfo) => {
  // console.log(userInfo);
  const { data } = await $axios.put(
    `users/${userInfo.id}/state/${userInfo.mg_state}`
  );
  // console.log(data);
  if (data.meta.status !== 200) {
    userInfo.mg_state = !userInfo.mg_state;
    return ElMessage({
      type: 'error',
      showClose: true,
      message: '更新用户状态失败！',
    });
  }
  ElMessage({
    type: 'success',
    showClose: true,
    message: '更新用户状态成功！',
  });
};
// *对话框显示与隐藏
let addDialogVisible = ref(false);
// * 点击展示
const showAddDialog = () => {
  addDialogVisible.value = true;
};

// *自定义规则
let checkEmail = (rule, value, callback) => {
  const RegEmail =
    /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/;

  if (RegEmail.test(value)) return callback();

  callback(new Error('请输入合法的邮箱'));
};
let checkMobile = (rule, value, callback) => {
  const RegMobile =
    /^((13[0-9])|(14[0-9])|(15[0-9])|(17[0-9])|(18[0-9]))\d{8}$/;
  if (RegMobile.test(value)) return callback();

  callback(new Error('请输入合法的手机号'));
};
// *添加用户的表单数据
let addForm = reactive({
  username: '',
  password: '',
  email: '',
  mobile: '',
});

// *添加表单的验证规则对象
let addFormRules = reactive({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 10, message: '用户名长度在3~10个字符之间', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 15, message: '密码长度在6~15个字符之间', trigger: 'blur' },
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { validator: checkEmail, trigger: 'blur' },
  ],
  mobile: [
    { required: true, message: '请输入手机', trigger: 'blur' },
    { validator: checkMobile, checkEmail, trigger: 'blur' },
  ],
});

let addFormRef = ref(null);

// * 添加对话框 关闭重置表单
const addDialogClosed = () => {
  // console.dir(addFormRef);
  addFormRef._value.resetFields();
};
// * 添加用户
const addUser = () => {
  addFormRef._value.validate(async (valid) => {
    if (!valid) return;

    const { data: res } = await $axios.post('users', addForm);
    console.log(res);
    if (res.meta.status !== 201)
      return ElMessage({ type: 'error', message: '添加用户失败！' });
    ElMessage({ type: 'success', message: '添加用户成功！', showClose: true });
    // 隐藏 添加表框
    addDialogVisible.value = false;
    getUserList();
  });
};

// * 点击 展示修改用户 的对话框
async function showEditDialog(id) {
  const { data: res } = await $axios.get(`users/${id}`);
  if (res.meta.status !== 200)
    return ElMessage({
      type: 'error',
      message: '查询用户信息失败!',
      showClose: true,
    });

  editForm.id = res.data.id;
  editForm.username = res.data.username;
  editForm.email = res.data.email;
  editForm.mobile = res.data.mobile;

  editDialogVisible.value = true;
}
// * 控制修改用户框的显示与隐藏
let editDialogVisible = ref(false);

// *查询到的用户信息对象
let editForm = reactive({
  id: null,
  username: '',
  email: '',
  mobile: '',
});

let editFormRules = reactive({
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { validator: checkEmail, trigger: 'blur' },
  ],
  mobile: [
    { required: true, message: '请输入手机', trigger: 'blur' },
    { validator: checkMobile, checkEmail, trigger: 'blur' },
  ],
});

let editFormRef = ref(null);

const editFormClosed = () => {
  // console.log(editFormRef._value);
  editFormRef._value.resetFields();
};

const editUser = (id) => {
  editFormRef._value.validate(async (valid) => {
    if (!valid) return;
    const { data: res } = await $axios.put('users/' + editForm.id, {
      email: editForm.email,
      mobile: editForm.mobile,
    });

    if (res.meta.status !== 200)
      return ElMessage({
        type: 'error',
        message: '更新用户信息失败！',
        showClose: true,
      });
    editDialogVisible.value = false;
    getUserList();
    ElMessage({
      type: 'success',
      message: '更新用户信息成功！',
      showClose: true,
    });
  });
};

// *删除 用户
const removeUserById = async (id) => {
  const result = await ElMessageBox.confirm(
    '此操作将永久删除该用户，是否继续?',
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).catch((err) => err);
  if (result !== 'confirm')
    return ElMessage({
      type: 'info',
      message: '已取消删除用户',
      showClose: true,
    });

  const { data } = await $axios.delete('users/' + id);

  if (data.meta.status !== 200)
    return ElMessage({
      type: 'error',
      message: '删除用户失败！',
      showClose: true,
    });

  ElMessage({
    type: 'success',
    message: '删除用户成功',
    showClose: true,
  });
  getUserList();
};

//  设置 用户的权限 对话框
let setRoleDialogVisible = ref(false);
// 需要 被分配角色的信息
let userInfo = ref({});
// 获取的 角色列表
let rolesList = ref([]);
// select 选择的值
let selectRoleId = ref(null);
//
const setRoles = async (Info) => {
  userInfo.value = Info;

  const { data } = await $axios.get('roles');
  // console.log(data);
  if (data.meta.status !== 200)
    return ElMessage({ type: 'error', message: '获取数据列表失败' });
  rolesList.value = data.data;
  console.log(rolesList);

  setRoleDialogVisible.value = true;
};
//  确认点击
const saveRoleInfo = async () => {
  if (!selectRoleId)
    return ElMessage({
      type: 'error',
      message: '请选择要分配的角色',
      showClose: true,
    });

  const { data } = await $axios.put(`users/${userInfo.value.id}/role`, {
    rid: selectRoleId.value,
  });
  console.log(data);
  if (data.meta.status !== 200)
    return ElMessage({
      type: 'error',
      message: '更新角色失败',
      showClose: true,
    });

  ElMessage({
    type: 'success',
    message: '更新角色成功!',
    showClose: true,
  });

  getUserList();
  setRoleDialogVisible.value = false;
};
</script>

<style scoped></style>
